﻿using Microsoft.EntityFrameworkCore;
using XYAC.Framework.MonitorTireMaterialOnline.Entities;

namespace XYAC.Framework.MonitorTireMaterialOnline.Context
{
    public abstract class HisDataContext : DbContext
    {
        private bool? _dbFileCreated;

        public virtual DbSet<SpecValTable> SpecVal { get; set; } = null!;
        public virtual DbSet<WeightData> WeightData { get; set; } = null!;

        public bool GetDbFileCreated()
        {
            if (!_dbFileCreated.HasValue)
            {
                string connectionStr = Database.GetConnectionString();

                // 提取 Data Source 的值
                var dataSourceIndex = connectionStr.IndexOf("Data Source=", StringComparison.OrdinalIgnoreCase);
                if (dataSourceIndex < 0)
                {
                    throw new InvalidOperationException("连接字符串中未找到 'Data Source='。");
                }

                // 提取数据库文件路径部分（直到第一个分号或字符串结尾）
                int endIndex = connectionStr.IndexOf(";", dataSourceIndex);
                var dbFilePath = endIndex > dataSourceIndex
                    ? connectionStr.Substring(dataSourceIndex + "Data Source=".Length, endIndex - dataSourceIndex - "Data Source=".Length).Trim()
                    : connectionStr.Substring(dataSourceIndex + "Data Source=".Length).Trim();

                // 获取完整路径并检查文件是否存在
                var fullPath = System.IO.Path.GetFullPath(dbFilePath);
                _dbFileCreated = System.IO.File.Exists(fullPath);
            }

            return _dbFileCreated.Value;
        }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

    }
}
